package com.hxzy.controller.shengpi;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxzy.common.annon.Log;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.enums.BusinessType;
import com.hxzy.common.vo.R;
import com.hxzy.controller.admin.BaseController;
import com.hxzy.dto.shengpi.CategorySearchDTO;
import com.hxzy.entity.shengpi.ShengpiCategory;
import com.hxzy.service.shengpi.ShengpiCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 项目审批分类
 * @author Administrator
 */
@Log4j2
@Api(tags = "项目审批分类API")
@RestController
@RequestMapping(value = "/api/xmsp/category")
public class SpCategoryController extends BaseController {


    @Autowired
    private ShengpiCategoryService shengpiCategoryService;

    @Autowired
    private RedissonClient  redissonClient;

    @PreAuthorize(value = "@ss.hasAuthority('xmsp:category:list')")
    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R search(CategorySearchDTO searchDTO){
        super.startPageHelper();

        QueryWrapper<ShengpiCategory> queryWrapper=new QueryWrapper<>();
        if(StrUtil.isNotBlank(searchDTO.getName())){
            queryWrapper.like("name", searchDTO.getName());
        }
        List<ShengpiCategory> categoryList = this.shengpiCategoryService.list(queryWrapper);
        return super.pageToPageVO(categoryList);
    }

    //@RateLimiter(time = 60,count = 5)
    @PreAuthorize(value = "@ss.hasAuthority('xmsp:category:add')")
    @Log(title = "审批分类",businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增")
    @PostMapping
    public R add(@RequestBody @Valid ShengpiCategory shengpiCategory) throws IllegalAccessException {

        //java  单机版 非公平锁
        //Lock lock=new ReentrantLock();
        //分布式布
        RLock lock = this.redissonClient.getLock("ShengpiCategory:add");

        try {
            boolean result= lock.tryLock(2, TimeUnit.SECONDS);
            if(result){
                //值必须是唯一的
                super.adminValidateExistsValue(shengpiCategory,"name",shengpiCategory.getName());

                boolean save=this.shengpiCategoryService.add(shengpiCategory);
                return super.toR(save);

            }else{
                return R.build(AckCode.COMMON_FRE_OPERATION);
            }

        } catch (InterruptedException e) {
            log.error(e);
            return R.build(AckCode.FAIL);
        }finally {
            lock.unlock();
        }
    }

    @PreAuthorize(value = "@ss.hasAuthority('xmsp:category:edit')")
    @Log(title = "审批分类",businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改")
    @PutMapping
    public R update(@RequestBody @Valid ShengpiCategory shengpiCategory) throws IllegalAccessException {
        //值必须是唯一的
        super.adminValidateExistsValue(shengpiCategory,"name",shengpiCategory.getName());
        boolean save=this.shengpiCategoryService.updateById(shengpiCategory);
        return super.toR(save);
    }

    @PreAuthorize(value = "@ss.hasAuthority('xmsp:category:query')")
    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R findById(@PathVariable(value = "id") String id)  {
        ShengpiCategory shengpiCategory = this.shengpiCategoryService.getById(id);
        if(shengpiCategory==null){
            return R.build(AckCode.NOT_FOUND_DATA);
        }
        return R.okHasData(shengpiCategory);
    }
}
